package org.darkforest.merchant.service.impl;

import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.darkforest.common.services.SettingService;
import org.darkforest.common.services.SimpleRedisService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.ExpressMapper;
import org.darkforest.dao.mapper.MemberMapper;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.merchant.service.OrderService;
import org.darkforest.merchant.service.WXMessageService;
import org.darkforest.merchant.utils.HttpTool;
import org.darkforest.model.Express;
import org.darkforest.model.Member;
import org.darkforest.model.Order;
import org.darkforest.model.OrderCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by admin on 2015/8/26.
 */
@Service("wXMessageService")
public class WXMessageServiceImpl implements WXMessageService {
    @Autowired
    private SettingService settingService;
    @Autowired
    private SimpleRedisService redisService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ExpressMapper expressMapper;
    @Autowired
    private OrderService orderService;
    @Override
    public String getAccessToken() throws Exception {
        String access_token = redisService.getByKey("wx_access_token");
        //redis中没有access_token数据时，发送http请求获取
        if(StringUtils.isEmpty(access_token)){
            String appId = settingService.getSettingInfo(SettingNameEnum.WXPAY_APP_ID);
            String appSecret = settingService.getSettingInfo(SettingNameEnum.WXPAY_APP_SECRET);
            String charset = settingService.getSettingInfo(SettingNameEnum.WXPAY_INPUT_CHARSET);
            String result = HttpTool.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret, charset);
            JSONObject jsonObject = JSONObject.fromObject(result);
            access_token = jsonObject.getString("access_token");
            //缓存access_token到redis中
            redisService.setValueInTime("wx_access_token",access_token,7200L);
        }
        return access_token;
    }

    public  void setWXMessage(Integer orderId){
        Order order=orderService.selectById(orderId);
        Member member = memberMapper.getMemberById(order.getBuyerId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dates = sdf.format(date);
        String  openId ="";
        String  orderSn = order.getOrderSn()!=null?order.getOrderSn().toString():"";//订单号
        String  shipCode ="";
        String text ="";
        if(member != null && member.getMemberWxOpenid() != null){
            openId =member.getMemberWxOpenid();
            if(order.getShippingCode()!=null&&!order.getShippingCode().equals("")) {
                shipCode = order.getShippingCode();//快递单号
                OrderCommon orderCommon = orderService.getOrderCommonById(order.getOrderId());
                String shippingTime = orderCommon.getShippingTime() != null ? DateUtil.toIntDateString(orderCommon.getShippingTime()) : sdf.format(new Date());
                Express express = expressMapper.selectByExpressId(orderCommon.getShippingExpressId());
                String expressName = express.geteName();
                text = "您的订单" + orderSn + "已通过" + expressName + "于" + shippingTime + "已发货，快递单号为" + shipCode + "请注意查收，谢谢!";
            }else{
                text = "您的订单" + orderSn + "于" + dates + "已发货，请注意查收，谢谢!";
            }
            String param = "{\"touser\":\""+openId+"\",\n" +
                    "    \"msgtype\":\"text\",\n" +
                    "    \"text\":{\n" +
                    "    \"content\":\""+text+"\"}\n" +
                    "}";

            String access_token = null;
            try {
                access_token = this.getAccessToken();
                String result = HttpTool.sendPostMessage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token, param, "UTF-8");
                System.out.println(result);
                System.out.println("成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
